import { Base64 } from 'js-base64'
import 'vant/es/toast/style'
import { appStore } from '@/stores/appStore/appStore'
import pinia from "@/stores/index"
import { ImagePreview ,Toast,Dialog} from 'vant'
import { useRoute, useRouter, type LocationQueryRaw } from 'vue-router'
import { store } from '@/stores/allStores'
import { storeToRefs } from 'pinia'

const app = appStore(pinia)

/** 
 * @普通样式消息确认弹窗
*/
interface moadlType{
  title?:string,
  message:string,
  showCancelButton?:boolean,
  confirmButtonText?:string,
  confirmButtonColor:string,
  cancelButtonColor?:string,
  cancelButtonText?:string
}
export function showModal(content:moadlType){
  return new Promise<void>((resolve,reject)=>{
    if(!content.confirmButtonColor){
      content.confirmButtonColor = store.common.themeColorValue
    }
    Dialog.confirm(content).then(()=>{
      resolve()
    }).catch(()=>{
      reject()
    })
  })
}

/** 
 * @清空缓存页面和缓存历史
*/
function clearHistory() {
  const route = useRoute()
  store.routerStore.clearCacheList() //清空缓存组件
  let historyLength = window.history.length
  let path = route.path
  let query = route.query
  window.history.go(-historyLength)
}

/**
 * @relaunch 清楚所有缓存，跳转新页面
 */
export function relaunch(option:{url: string, param: LocationQueryRaw}) {
  clearHistory()
  const router = useRouter()
  router.push({ path: option.url, query: option.param })
}
/**
 * @switchTab 清楚所有缓存，跳转tab
 */
export function switchTab(url: string) {
  clearHistory()
  const router = useRouter()
  router.push({ path: url,})
}
/**
 * getScrollTop 获取页面滚动高度
 */
export function getScrollTop(){
 return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
}
/**
 * pageScrollTop 监听页面滚动
 * @pageScrollTop.scrollTop 返回页面滚动高度 
 * @setListener 监听滚动
 * @removeListener 取消监听
 * @fn 监听事件调用
 */
export class pageScrollTop {
  fn
  scrollTop = 0
  bottom = 22
  constructor(fnc:any) {
    this.fn = fnc
  };
  setListener() {
    window.addEventListener('scroll', this.fn, true)
  };
  removeListener() {
    window.removeEventListener('scroll', this.fn, true)
  };
}

/**
 * 路由参数加密
 * 返回统一对象{payload：string}
 * @paramEncode
 */
export function paramEncode(param: object) {
  return { payload: Base64.encode(JSON.stringify(param)) }
}
/**
 * 路由参数解码
 * @paramDecode
 * 解码后样式 payload:{...object},无参数则为null
 */
export function paramDecode() {
  const route = useRoute()
  let param = route.query.payload
  if (typeof param === 'string') {
    return JSON.parse(Base64.decode(param))
  } else {
    return null
  }
}

/**
 * 分页类型
 * @pageData { size: 10,current: 1,total: 0,}
 * @fn constructor(fnc: Function) 接口方法
 * @getData getData(param) param自参数，return分页数据
 * @resetPage pageData重新初始化
*/
export class pageList {
  fn: Function
  loadState = ''
  pageData = {
    size: 10,
    current: 1,
    total: 0,
  }
  constructor(fnc: Function) {
    this.fn = fnc
  };
  getData(params: object): Promise<any> {
    let param = { ...params, ...this.pageData }
    return this.fn(param)
  };
  resetPage() {
    this.pageData = Object.assign(this.pageData, {
      size: 10,
      current: 1,
      total: 0,
    })
  }
}

/**
* 大图预览
* @params 图片地址
**/
export function imgPreview(imgList: string[]) {
  return ImagePreview(imgList)
}

/**
*vite图片地址
* @params 图片地址
**/
export function getImgPath(params: string): string {
  return new URL(params, import.meta.url).href
}
/**
* @params 图片地址
* @autoZoom （0，1，2，3）对应不同压缩等级，默认：0 不压缩
**/
export function getImage(value: string | null, autoZoom = 0) {
  if (!value) {
    return getImgPath('../assets/static/common/no_pic.png')
  }
  if (value.startsWith('http')) {
    return value
  } else {
    let autoZoomList = ['', '?imageMogr2/format/jpg/blur/1x0/quality/90', '?imageMogr2/auto-orient/thumbnail/750x/blur/1x0/quality/80', '?imageMogr2/auto-orient/thumbnail/320x/blur/1x0/quality/80']
    return getImgPath(app.staticUrl + value + autoZoomList[autoZoom])
  }
}

/**
 * 弹窗提示
 * **/
export const toast = Toast

/**
 * 是否为微信环境
 * **/
export function isWeixin() {
  let ua = navigator.userAgent.toLowerCase()
  if (String(ua.match(/MicroMessenger/i)) === "micromessenger") {
    return true
  } else {
    return false
  }
}